package cn.itcast.Rainbow_self_mention.Server;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.InetSocketAddress;

import cn.itcast.Rainbow_self_mention.Activity.Detail_for_rec;
import cn.itcast.Rainbow_self_mention.Activity.Detail_for_sub;
import cn.itcast.Rainbow_self_mention.Server.Handler.FileUploadServerHandler;
import cn.itcast.Rainbow_self_mention.Tools.imfor;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class PictureReceiver extends Service {
    /* operation=1-------查数据
     * operation=2-------增加数据
     * operation=3-------修改数据
     * operation=4-------删除数据
     *
     * operation=11-------返回查数据
     * operation=12-------返回增加结果
     * operation=13-------返回修改结果
     * operation=14-------返回删除结果
     *
     */

    Channel ch1;
    Channel ch2;
    String ip = imfor.ip;
    Boolean link = false;
    sender sender;
    Handler rec = Detail_for_rec.handler;
    Handler sub = Detail_for_sub.handler;

    public IBinder onBind(Intent intent) {
        sender = new sender();
        return sender;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        SDKInitializer.initialize(getApplicationContext());
        link();
    }

public void link(){
    NioEventLoopGroup group = new NioEventLoopGroup();
    ChannelFuture bs1 = new Bootstrap()
            .group(group)
            .channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<NioSocketChannel>() {
                protected void initChannel(final NioSocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new LineBasedFrameDecoder(2048));
                    ch.pipeline().addLast(new StringEncoder());
                    ch.pipeline().addLast(new StringDecoder());
                    ch.pipeline().addLast("input", new ChannelInboundHandlerAdapter() {
                        public void channelActive(ChannelHandlerContext ctx) {
                        link=true;
                            Message re = rec .obtainMessage();
                            Message su = sub .obtainMessage();
                            Bundle bundle = new Bundle();
                            bundle.putString("sentresult", "34");
                            re.setData(bundle);
                            su.setData(bundle);
                            rec.sendMessage(re);
                            sub.sendMessage(su);
                        }

                        @Override
                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                            super.channelRead(ctx, msg);
                            operation(msg);
                        }

                        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                            link=false;
                            Message re = rec .obtainMessage();
                            Message su = sub .obtainMessage();
                            Bundle bundle = new Bundle();
                            bundle.putString("sentresult", "35");
                            re.setData(bundle);
                            su.setData(bundle);
                            rec.sendMessage(re);
                            sub.sendMessage(su);
                        }
                    });
                }
            })
            .connect(new InetSocketAddress(ip, 9521));
    ch1 = bs1.channel();
}

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(ch1!=null)
        { ChannelFuture cf1 = ch1.closeFuture();
            try {
                cf1.sync();

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        if(ch2!=null)
        {
            ChannelFuture cf2 = ch2.closeFuture();
            try {

                cf2.sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    }

    public class sender extends Binder {

        public void connectP(int port) {
            NioEventLoopGroup group = new NioEventLoopGroup();
            ChannelFuture bs2 = new Bootstrap()
                    .group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ObjectEncoder());
                            ch.pipeline().addLast(new ObjectDecoder(ClassResolvers.weakCachingConcurrentResolver(null)));
                            ch.pipeline().addLast(new FileUploadServerHandler());
                        }
                    })
                    .connect(new InetSocketAddress(ip, port));
            ch2 = bs2.channel();
        }

        public void relink() {
           link();

        }

        public void sm(String code,String name,int userid,String orderid)
        {
            if(link){
                if(code.equals("7")){
                    String m = "{" +
                            "\"Cop\":" + "\"7\"," +
                            "\"name\":" + "\"" + name + "\"," +
                            "\"userid\":" + "\"" + userid + "\"," +
                            "\"orderid\":" + "\"" + orderid + "\"," +
                            "}" + '\n';
                    ch1.writeAndFlush(m);
                }
                if(code.equals("8")){
                    String m = "{" +
                            "\"Cop\":" + "\"8\"," +
                            "\"id\":" + "\"" + name + "\"," +
                            "}" + '\n';
                    ch1.writeAndFlush(m);
                }
                if(code.equals("9")){
                    String m = "{" +
                            "\"Cop\":" + "\"9\"," +
                            "\"id\":" + "\"" + name + "\"," +
                            "}" + '\n';
                    ch1.writeAndFlush(m);
                }
            }
            else
            {
                Message re = rec .obtainMessage();
                Message su = sub .obtainMessage();
                Bundle bundle = new Bundle();
                bundle.putString("sentresult", "35");
                re.setData(bundle);
                su.setData(bundle);
                rec.sendMessage(re);
                sub.sendMessage(su);
                relink();
            }

        }

    }

    //**************************************返回检验结果解析处*****************************
    public void operation(Object msg) throws JSONException {
        String m = msg.toString();
        Log.i("jieshoudao",m);
        JSONObject jsonObject = new JSONObject(m);
        //服务器图片打开成功
        if (jsonObject.getString("Cop").equals("71")) {
            sender.connectP(jsonObject.getInt("port"));
            Message re = rec .obtainMessage();
            Message su = sub .obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "1");
            re.setData(bundle);
            su.setData(bundle);
            rec.sendMessage(re);
            sub.sendMessage(su);

        }
        //服务器找不到图片
        if (jsonObject.getString("Cop").equals("72")) {
            Message re = rec .obtainMessage();
            Message su = sub .obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "2");
            re.setData(bundle);
            su.setData(bundle);
            rec.sendMessage(re);
            sub.sendMessage(su);
        }
        //服务器正在回传图片
        if (jsonObject.getString("Cop").equals("73")) {
            Message re = rec .obtainMessage();
            Message su = sub .obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "3");
            re.setData(bundle);
            su.setData(bundle);
            rec.sendMessage(re);
            sub.sendMessage(su);

        }
        //回传完成
        if (jsonObject.getString("Cop").equals("74")) {
            Message re = rec .obtainMessage();
            Message su = sub .obtainMessage();
            Bundle bundle = new Bundle();
            bundle.putString("sentresult", "4");
            re.setData(bundle);
            su.setData(bundle);
            rec.sendMessage(re);
            sub.sendMessage(su);

        }

    }

}

